package bll

import (
	"context"

	"manager/event"
	"manager/model"
	"manager/model/entity"
	"manager/store"
	"manager/store/postgres"
	"time"

	"manager/auth"
)

type voiceSetting struct {
	iVoiceSetting store.IVoiceSetting
}

var VoiceSetting = &voiceSetting{
	iVoiceSetting: postgres.VoiceSetting,
}

func (a *voiceSetting) init() func() {
	return func() {}
}

func (a *voiceSetting) onEvent(*event.Data) {}

// Create 创建
func (a *voiceSetting) Create(ctx context.Context, in *model.VoiceSettingCreateRequest) error {
	var (
		err error
	)

	// 获取用户Id
	in.UserId, _ = auth.ContextUserID(ctx)

	// 构建创建现场数据
	c := buildVoiceSetting(in)
	_, err = a.iVoiceSetting.Create(ctx, c)
	return err
}

// Update 更新
func (a *voiceSetting) Update(ctx context.Context, in *model.VoiceSettingUpdateRequest) error {
	var (
		dict = make(map[string]interface{})
	)

	updateAt := time.Now().Unix()
	in.UpdatedAt = &updateAt

	if in.UserId != nil {
		dict["user_id"] = in.UserId
	}

	if in.SeriesType != nil {
		dict["series_type"] = in.SeriesType
	}

	if in.UpdatedAt != nil {
		dict["updated_at"] = in.UpdatedAt
	}

	// do other update here

	return a.iVoiceSetting.Update(ctx, in.Id, dict)
}

// Delete 删除
func (a *voiceSetting) Delete(ctx context.Context, in *model.VoiceSettingDeleteRequest) error {
	return a.iVoiceSetting.Delete(ctx, in.Id)
}

// List 列表查询
func (a *voiceSetting) List(ctx context.Context, in *model.VoiceSettingListRequest) (*model.VoiceSettingListResponse, error) {
	var (
		err   error
		total int
		list  []*entity.VoiceSetting
		out   = &model.VoiceSettingListResponse{}
	)

	if total, list, err = a.iVoiceSetting.List(ctx, in); err != nil {
		return nil, err
	}

	out.Total = total
	out.List = model.VoiceSettingsEntityToDto(list)

	return out, nil
}

// Find 列表查询
func (a *voiceSetting) Find(ctx context.Context, in *model.VoiceSettingInfoRequest) (*model.VoiceSettingInfo, error) {
	var (
		err  error
		data *entity.VoiceSetting
		out  = &model.VoiceSettingInfo{}
	)

	if data, err = a.iVoiceSetting.Find(ctx, in); err != nil {
		return nil, err
	}

	out = model.VoiceSettingEntityToDto(data)
	return out, nil
}

// buildVoiceSetting 构建创建数据现场
func buildVoiceSetting(in *model.VoiceSettingCreateRequest) *entity.VoiceSetting {
	// todo: check the entity is required
	return &entity.VoiceSetting{

		UserId: in.UserId,

		SeriesType: in.SeriesType,

		CreatedAt: time.Now().Unix(),

		UpdatedAt: time.Now().Unix(),
	}
}
